package com.innovation.ic.im.end.base.thread.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.innovation.ic.b1b.framework.util.HanziToPinyinUtils;
import com.innovation.ic.im.end.base.model.im_erp9.Account;
import com.innovation.ic.im.end.base.model.im_erp9.AccountRelation;
import com.innovation.ic.im.end.base.model.im_erp9.ChatPair;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.RabbitMqConstants;
import com.innovation.ic.im.end.base.pojo.enums.AccountIntegrationEnum;
import com.innovation.ic.im.end.base.service.im_erp9.AccountRelationService;
import com.innovation.ic.im.end.base.service.im_erp9.AccountService;
import com.innovation.ic.im.end.base.service.im_erp9.ChatPairService;
import com.innovation.ic.im.end.base.thread.AbstractThread;
import com.innovation.ic.im.end.base.value.config.SystemConfig;
import com.rabbitmq.client.*;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;

/**
 * @desc   监听erp新增、修改供应商协同账号队列
 * @author linuo
 * @time   2023年4月19日14:22:15
 */
public class ListenErpScAccountAddUpdateQueueThread extends AbstractThread implements Runnable{
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /** erp交换机 */
    private String exchange;

    private AccountRelationService accountRelationService;

    private ChatPairService chatPairService;

    public ListenErpScAccountAddUpdateQueueThread(Channel channel, String exchange, AccountService accountService, AccountRelationService accountRelationService, ChatPairService chatPairService, SystemConfig systemConfig) {
        this.channel = channel;
        this.exchange = exchange;
        this.accountService = accountService;
        this.accountRelationService = accountRelationService;
        this.chatPairService = chatPairService;
        this.systemConfig = systemConfig;
    }

    @SneakyThrows
    @Override
    public void run() {
        String routingKey = RabbitMqConstants.ERP_SC_ACCOUNT_ADD_UPDATE_QUEUE;
        String queue = routingKey;
        channel.queueBind(queue, exchange, routingKey);
        channel.queueDeclare(queue, true, false, false, null);
        channel.exchangeDeclare(exchange, RabbitMqConstants.DIRECT_TYPE, true);
        Consumer callback = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
                String bodyString = new String(body);
                logger.info("接收到的队列:[{}]的消息为:[{}]", queue, bodyString);
                try {
                    JSONObject jsonObject = JSON.parseObject(bodyString);
                    if(jsonObject != null && !jsonObject.isEmpty()){
                        // 获取消息名称
                        String msgName = jsonObject.getString(RabbitMqConstants.MESSAGE_NAME_FIELD);
                        if(!msgName.equals(RabbitMqConstants.ERP_SC_ACCOUNT_ADD_UPDATE_QUEUE)){
                            logger.info("mq消息中的方法为:[{}],与当前监听方法:[{}]不一致,不进行后续处理", msgName, RabbitMqConstants.ERP_GROUP_DELETE_QUEUE);
                            return;
                        }

                        // 获取消息体
                        JSONObject json = (JSONObject) jsonObject.get(RabbitMqConstants.MESSAGE_BODY_FIELD);
                        if(json != null && !json.isEmpty()){
                            String id = json.getString(RabbitMqConstants.ID);

                            // 判断账号数据是否存在
                            ServiceResult<Account> historyDataResult = accountService.findById(id);
                            Account historyData = historyDataResult.getResult();
                            if(historyData == null){
                                // 创建账号数据
                                Account account = new Account();
                                account.setId(id);
                                account.setRealName(json.getString(RabbitMqConstants.REAL_NAME));
                                account.setUsername(json.getString(RabbitMqConstants.USER_NAME));
                                account.setMobile(json.getString(RabbitMqConstants.MOBILE));
                                account.setSupplierName(json.getString(RabbitMqConstants.SUPPLIER_NAME));
                                account.setIntegration(AccountIntegrationEnum.SC_CORRELATION.getCode());

                                // 获取用户名的拼音信息
                                String pinyin = HanziToPinyinUtils.getPinyin(account.getRealName());
                                account.setPinYin(pinyin);
                                account.setCapitalInitial(pinyin.substring(0, 1).toUpperCase());

                                ServiceResult<Integer> serviceResult = accountService.saveAccount(account);
                                Integer result = serviceResult.getResult();
                                if(result != null && result > 0){
                                    logger.info("供应商协同账号数据创建成功");

                                    // 创建账号关系表数据
                                    saveAccountRelation(json);

                                    // 创建供应商协同与系统账号的聊天对数据
                                    String userName = json.getString(RabbitMqConstants.USER_NAME);
                                    String systemAccount = systemConfig.getAccount();
                                    createScSystemAccountChatPairData(userName, systemAccount);
                                }
                            }else{
                                historyData.setRealName(json.getString(RabbitMqConstants.REAL_NAME));
                                historyData.setUsername(json.getString(RabbitMqConstants.USER_NAME));
                                historyData.setMobile(json.getString(RabbitMqConstants.MOBILE));
                                historyData.setSupplierName(json.getString(RabbitMqConstants.SUPPLIER_NAME));
                                historyData.setIntegration(AccountIntegrationEnum.SC_CORRELATION.getCode());

                                // 获取用户名的拼音信息
                                String pinyin = HanziToPinyinUtils.getPinyin(historyData.getRealName());
                                historyData.setPinYin(pinyin);
                                historyData.setCapitalInitial(pinyin.substring(0, 1).toUpperCase());
                                ServiceResult<Integer> serviceResult = accountService.updateAccountData(historyData);
                                Integer result = serviceResult.getResult();
                                if(result != null && result > 0){
                                    logger.info("供应商协同账号数据更新成功");

                                    // 查询是否有账号关系表数据
                                    ServiceResult<AccountRelation> serviceResult1 = accountRelationService.selectDataByScSaleAccountId(json.getString(RabbitMqConstants.ID), json.getString(RabbitMqConstants.PURCHASE_ACCOUNT_ID));
                                    AccountRelation accountRelation = serviceResult1.getResult();
                                    if(accountRelation == null){
                                        // 创建账号关系表数据
                                        saveAccountRelation(json);
                                    }

                                    // 创建供应商协同与系统账号的聊天对数据
                                    String userName = json.getString(RabbitMqConstants.USER_NAME);
                                    String systemAccount = systemConfig.getAccount();
                                    createScSystemAccountChatPairData(userName, systemAccount);
                                }
                            }
                        }
                    }
                    logger.info("erp新增、修改供应商协同账号队列消息处理结束");
                } catch (Exception e) {
                    logger.error("监听队列:[{}]时出现问题,原因:", queue, e);
                }
            }
        };
        channel.basicConsume(queue, true, callback);
    }

    /**
     * 保存账号关系表数据
     * @param json json数据
     */
    private void saveAccountRelation(JSONObject json){
        // 供应商账号对应的采购账号id
        String purchaseAccountId = json.getString(RabbitMqConstants.PURCHASE_ACCOUNT_ID);
        if(!Strings.isNullOrEmpty(purchaseAccountId)){
            String scAccountId = json.getString(RabbitMqConstants.ID);

            // 删除历史账号关系表数据
            accountRelationService.deleteByScAccountId(scAccountId);

            // 删除历史供应商协同账号与采购的聊天对数据
            chatPairService.deleteScChatPairData(scAccountId);

            // 创建账号关系表数据
            AccountRelation accountRelation = new AccountRelation();
            accountRelation.setSaleAccountId(purchaseAccountId);
            accountRelation.setScAccountId(scAccountId);
            ServiceResult<Integer> serviceResult1 = accountRelationService.saveAccountRelation(accountRelation);
            Integer result1 = serviceResult1.getResult();
            if(result1 != null && result1 > 0){
                logger.info("创建账号关系表数据成功");

                // 创建供应商协同账号与采购账号的聊天对
                createScSaleAccountChatPair(scAccountId, purchaseAccountId);
            }
        }
    }

    /**
     * 创建供应商协同与系统账号的聊天对数据
     * @param scAccount 供应商协同账号
     * @param systemAccount 系统账号
     */
    private void createScSystemAccountChatPairData(String scAccount, String systemAccount){
        // 查询供应商协同账号与系统账号的聊天对数据
        ServiceResult<List<ChatPair>> serviceResult1 = chatPairService.selectDataByAccount(scAccount, systemAccount);
        List<ChatPair> result1 = serviceResult1.getResult();
        if(result1 == null || result1.size() == 0){
            // 创建供应商协同账号与系统账号的聊天对
            createScSaleAccountChatPair(scAccount, systemAccount);
        }
    }

    /**
     * 创建供应商协同账号与采购或系统账号的聊天对
     * @param scAccountId 供应商协同账号
     * @param purchaseAccountId 采购或系统账号
     */
    private void createScSaleAccountChatPair(String scAccountId, String purchaseAccountId) {
        ServiceResult<Account> scAccountResult = accountService.findByAccount(scAccountId);
        Account scAccount = scAccountResult.getResult();

        ServiceResult<Account> saleAccountResult = accountService.findByAccount(purchaseAccountId);
        Account saleOrSystemAccount = saleAccountResult.getResult();

        if(scAccount != null && saleOrSystemAccount != null){
            String scAccountUsername = scAccount.getUsername();
            String saleAccountUsername = saleOrSystemAccount.getUsername();

            // 获取当前chatPair表中最大的code
            ServiceResult<Integer> serviceResult = chatPairService.getMaxCode();
            Integer code = serviceResult.getResult();
            if(code != null && !Strings.isNullOrEmpty(scAccountUsername) && !Strings.isNullOrEmpty(saleAccountUsername)){
                code++;
                ChatPair chatPair = new ChatPair();
                chatPair.setFromUserAccount(scAccountUsername);
                chatPair.setToUserAccount(saleAccountUsername);
                chatPair.setCode(code);
                chatPairService.saveChatPair(chatPair);

                chatPair = new ChatPair();
                chatPair.setFromUserAccount(saleAccountUsername);
                chatPair.setToUserAccount(scAccountUsername);
                chatPair.setCode(code);
                ServiceResult<Boolean> serviceResult1 = chatPairService.saveChatPair(chatPair);
                Boolean result = serviceResult1.getResult();
                if(result){
                    logger.info("创建供应商协同账号与采购账号的聊天对成功");
                }
            }
        }
    }
}